
package com.compuvest.web;

// <editor-fold defaultstate="collapsed" desc="import">
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// </editor-fold>

public class AdvertArray implements java.io.Serializable {

// <editor-fold defaultstate="collapsed" desc="init">
    public static final Logger log = LoggerFactory.getLogger(AdvertArray.class);

    public static final String VERSION = "AdvertArray v2.1 2008-04-02";

    public ServletContext context;
    public MySQL sb;

    private static String excelURL;
  
    private static Random rgen;
    private static Map<Integer,Item[]> firstItemsArray;		// first page
    private static Map<Integer,Item[]> categoryItemsArray;	// every category pages
    private static Map<Integer,Item[]> subcatItemsArray;	// every subcategory pages

    private static String mainMenu;
    public static Map<Integer,String> categoryMap;
    public static Map<Integer,ArrayList<Category>> subcatMap;
    public static String excelFiles;

    public static String country;
    public static String state;
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="AdvertArray()">

    public AdvertArray() {
    }

    public AdvertArray(ServletContext context, MySQL database) {
        this.context = context;
        this.sb = database;

        excelURL = context.getInitParameter("AdvertServer") + "excel/";
        log.info("exel=" + excelURL);

        rgen = new Random();

        log.info("Init: " + VERSION);
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="fillArray()">

    public void fillArray() {

        StringBuilder out = new StringBuilder(100);

        firstItemsArray = sb.getAdvertItemsFirstPage();
        out.append("\n\tfirstPage...\t").append(firstItemsArray.size());

        categoryItemsArray = sb.getAdvertItemsCategoryPage();
        out.append("\n\tcategoryPage...\t").append(categoryItemsArray.size());

        subcatItemsArray = sb.getAdvertItemsPage();
        out.append("\n\tsubcatPage...\t").append(subcatItemsArray.size());

        mainMenu = sb.selectMenuString();
        out.append("\n\tmainMenu...\t").append(mainMenu.length());

        sb.selectCategoryAll();
        out.append("\n\tcategoryAll...\t");

        country = sb.selectCountryString();
        out.append("\n\tcountry...\t").append(country.length());

        state = sb.selectStateString();
        out.append("\n\tstate...\t").append(state.length());

        excelFiles = loadExcelFile();
        out.append("\n\texcelFileList2...\t").append(excelFiles.length());

        System.out.println(out.toString());
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="getAdvertRandomCategory()">

    final int[] catIDs = { 573, 446, 9, 30, 304, 13, 397, 625 };

    public synchronized int getAdvertRandomCategory() {
        return catIDs[rgen.nextInt(catIDs.length)];
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="getString()">

    public synchronized String getString(String value, String defVal) {
        return value != null ? value : defVal;
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="getInt()">

    public synchronized int getInt(String value, int defInt) {

        int integer = defInt;
        try {
            integer = Integer.parseInt(value);
        }
        catch(Exception ignore) { }

        return integer;
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="getLong()">

    public synchronized long getLong(String value, long defInt) {

        long longValue = defInt;
        try {
            longValue = Long.parseLong(value);
        }
        catch(Exception ignore) { }

        return longValue;
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="getDouble()">

    public synchronized double getDouble(String value, double defDouble) {

        double dbl = defDouble;
        try {
            dbl = Double.parseDouble(value.replace('$','0'));
        }
        catch(Exception ignore) { }
        return dbl;
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="getFloatToInt()">

    public synchronized int getFloatToInt(String value, int defInt) {

        int result = defInt;
        float flt;
        try {
            flt = Float.parseFloat(value);
            result = (int)flt;
            if(flt < 0f)
                result = 0;
            else if(flt > 65536f)
                result = 65536;
        }
        catch(Exception ignore) { }

        return result;
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="getExcelFiles()">

    public synchronized String getExcelFiles() {
	return excelFiles;
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="getAdvertItemsFirstPage()">

    public synchronized Item[] getAdvertItemsFirstPage(int categoryID) {

        if(firstItemsArray == null) return null;

	Item[] advertItems = firstItemsArray.get(categoryID);
	if(advertItems == null) return null;

	// sort random array
        int randomPosition;
        Item temp;
	for(int i = 0; i < advertItems.length; i++) {
            randomPosition = rgen.nextInt(advertItems.length);
            temp = advertItems[i];
            advertItems[i] = advertItems[randomPosition];
            advertItems[randomPosition] = temp;
	}
	return advertItems;
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="getAdvertItemsCategoryPage()">

    public synchronized Item[] getAdvertItemsCategoryPage(int categoryID) {

        if(categoryItemsArray == null) return null;

	Item[] advertItems = categoryItemsArray.get(categoryID);
	if(advertItems == null) return null;

	// sort random array
	int randomPosition;
	Item temp;
	for(int i = 0; i < advertItems.length; i++) {
	    randomPosition = rgen.nextInt(advertItems.length);
	    temp = advertItems[i];
	    advertItems[i] = advertItems[randomPosition];
	    advertItems[randomPosition] = temp;
	}
	return advertItems;
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="getAdvertItemsPage()">

    public synchronized Item[] getAdvertItemsPage(int subcategoryID) {
	if(subcatItemsArray == null) return null;

	Item[] advertItems = subcatItemsArray.get(subcategoryID);
	if(advertItems == null) return null;

	// sort random array
	int randomPosition;
	Item temp;
	for(int i = 0; i < advertItems.length; i++) {
	    randomPosition = rgen.nextInt(advertItems.length);
	    temp = advertItems[i];
	    advertItems[i] = advertItems[randomPosition];
	    advertItems[randomPosition] = temp;
	}
	return advertItems;
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="getMainMenu()">

    public synchronized String getMainMenu(boolean isFromCookies, HttpSession session) {
	return new String(mainMenu);
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="getCountryList()">

    public synchronized String getCountryList(String countryCode) {
	return new String(country).replace("='" + countryCode + "'", "='" + countryCode + "' selected=selected");
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="getStateList()">

    public synchronized String getStateList(String stateCode) {
	return new String(state).replace("='" + stateCode + "'", "='" + stateCode + "' selected=selected");
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="refreshExcelFile()">

    public void refreshExcelFile() {
        excelFiles = loadExcelFile();
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="loadExcelFile()">

    private String loadExcelFile() {

        StringBuilder exline = new StringBuilder(100);
        try {
            URL url = new URL(excelURL);
            URLConnection conn = url.openConnection();
            conn.setDoInput(true);
            BufferedReader rdr = new BufferedReader(new InputStreamReader(conn.getInputStream()));

//            Pattern p = Pattern.compile(">([a-zA-Z0-9]+\\.xls)<");
            Pattern p = Pattern.compile(">([a-zA-Z0-9 ]+).xls<");
            Matcher m;

            String readLine;
            while((readLine = rdr.readLine()) != null) {
                m = p.matcher(readLine);
                if(m.find()) {
                    exline.append("<a class=exc href='").append(excelURL).append(m.group(1)).append(".xls'>");
                    exline.append(m.group(1)).append("</a>");
                }
            }
            rdr.close();
        }
        catch(Exception ex) { System.out.println("Error:compuvest.web.AdvertArray:loadExecelFile" + ex); }

        if(exline.length() != 0) {
            StringBuilder line = new StringBuilder(600);
            line.append("<fieldset>");
            line.append("<table border=0 cellpadding=0 width='100%' style='background-color:white;'>");
            line.append("<tr>");
            line.append("<td><img src='../images/excel/icon.png' border=0 height=30 /></td>");
            line.append("<td class=excel>Special Pricing In Excel<br/>Download Now</td>");
            line.append("</tr>");
            line.append("<tr>");
            line.append("<td colspan=2 style='border-top:2px solid red;padding:2px 0;'>").append(exline).append("</td>");
            line.append("</tr>");
            line.append("</table>");
            line.append("</fieldset>");

            return line.toString();
        }

        return "";
    }
// </editor-fold>

}

